package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func main() {
	getvideolist()
}
func getvideolist() (int, bool) {
	path, err := os.Getwd()
	if err != nil {
		fmt.Println("获取主程序路径失败:", err)
		//c.String(http.StatusInternalServerError, "Failed to open video file")
		return 1, false
	}
	filesPathDir := path + "/../video/mp4/"
	err = filepath.Walk(filesPathDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() && strings.HasSuffix(info.Name(), ".mp4") {
			//fmt.Println(strings.Split(path, "/"))
			filenames := strings.Split(path, "/")
			fmt.Println(filenames[len(filenames)-1])
			resval, resbool := Mp4tom3u8(filenames[len(filenames)-1], strings.Split(filenames[len(filenames)-1], ".")[0]+".ts")
			fmt.Println(resval, " ", resbool)
		}
		return nil
	})
	if err != nil {
		fmt.Println(err)
	}
	return 0, true
}
func Mp4tom3u8(inputfile, outputfile string) (int, bool) {
	// 打开视频文件
	path, err := os.Getwd()
	if err != nil {
		fmt.Println("获取主程序路径失败:", err)
		//c.String(http.StatusInternalServerError, "Failed to open video file")
		return 1, false
	}

	outputPath := path + "/../video/" + "ffmpeg"
	fmt.Println("outputPath:" + outputPath + "\noutputcheck" + outputPath + "/" + outputfile)
	// 检测是否已经转换
	if _, err := os.Stat(outputPath + "/" + outputfile); err == nil {
		fmt.Println("outputfile" + outputPath + "/" + outputfile)
		_ = fmt.Errorf("input file not found: %s", outputPath+"/"+outputfile)
		fmt.Println("已转换")
		return 0, true
	}
	filePathDir := path + "/../video/mp4/" + inputfile
	// 检查输入文件是否存在
	if _, err := os.Stat(filePathDir); os.IsNotExist(err) {
		_ = fmt.Errorf("input file not found: %s", filePathDir)
		return 2, false
	}

	// 创建输出目录
	if err := os.MkdirAll(outputPath, 0755); err != nil {
		_ = fmt.Errorf("failed to create output directory: %s", err)
		return 3, false
	}

	// 设置输出文件路径

	outputFilePath := filepath.Join(outputPath, outputfile)
	// 执行FFmpeg命令进行转换
	cmd := exec.Command("ffmpeg",
		"-i", filePathDir,
		"-c:v", "libx264",
		"-c:a", "aac",
		"-f", "hls",
		"-hls_time", "10",
		"-hls_list_size", "0",
		"-hls_base_url", "./",
		"-hls_segment_filename", filepath.Join(outputPath, strings.Split(inputfile, ".")[0]+"segment%03d.ts"),
		outputFilePath,
	)
	fmt.Println("outputFilePath", outputFilePath)
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		_ = fmt.Errorf("failed to convert video: %s", err)
		return 4, false
	}
	return 0, true
}
